<template>
  <TablePage>
    <template #top>
      <SearchForm title="用户管理" :keyword-search-data="[{ key: 'tollGateName', label: '用户名称' }]">
        <template #extraButtons>
          <a-button type="primary" @click="showCreateModal">新增用户</a-button>
        </template>
      </SearchForm>
    </template>
    <SlTable :columns="columns" row-key="id" :data-source="tableData" :loading="tableLoading">
      <template #bodyCell="{ column, record }: BodyCellOptions<PartialUserItem>">
        <div v-if="column.key === 'oper' && !record.admin">
          <a @click="showUpdateModal(record)">编辑</a>
          <a class="ml-2 text-red-400" @click="handleDelete(record)">删除</a>
          <br />
          <a @click="handleResetPwd(record)">重置密码</a>
        </div>
      </template>
    </SlTable>
    <CURDDialog
      ref="curdDialogIns"
      id-key="userId"
      :columns="columns"
      create-title="新增用户"
      update-title="编辑用户"
      delete-message="确认删除该用户吗？"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :model-rules="modelRules"
      :table-data="tableData"
      :oper-data="operData"
      :curd="curd"
      :reload-table="reloadTable"
      :delete-url-suffix-mode="2"
      :get-detail="getDetail"
      @open="open"
      @before-update-model="beforeUpdateModel"
      @before-ok="beforeOk"
    />
  </TablePage>
</template>
<script lang="ts" setup>
import { onMounted, ref, shallowRef } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { useCURD } from "/@/hooks/useCURD";
import { handleDateRowRender } from "/@/utils/common";
import { FormItemComponentType, CURDAction, CURDDialogExpose, CURDModalEvent } from "/@/components/CURDDialog/models";
import type { FormItemData, OperItem, ShowCURDModalOptions } from "/@/components/CURDDialog/models";
import type { TableProps } from "ant-design-vue";
import { message } from "ant-design-vue";
import { PatternKey } from "/@/utils/verify";
import { Api, getUserDetail, resetPwd } from "/@/api/home/user";
import type { UserItem, PartialUserItem } from "/@/api/home/user/models";
import type { BodyCellOptions } from "/@/types/antd";
import { getRoleList } from "/@/api/home/role";
import InfoModal from "/@/components/InfoModal";

const { t } = useI18n();
const columns = ref<TableProps<PartialUserItem>["columns"]>([
  {
    title: "账号",
    dataIndex: "userName",
  },
  {
    title: "姓名",
    dataIndex: "nickName",
  },
  {
    title: "邮箱",
    dataIndex: "email",
  },
  {
    title: "电话号码",
    dataIndex: "phonenumber",
  },
  {
    title: "备注",
    dataIndex: "remark",
  },
  {
    title: t("common.oper"),
    key: "oper",
    width: 100,
  },
]);
const model = ref<PartialUserItem>({
  userName: "",
  password: "",
  nickName: "",
  phonenumber: "",
  email: "",
  roleIds: [],
  remark: "",
});
const modelRules = ["userName", "password", "nickName", "roleIds"];
const modelFormSetting: FormItemData<PartialUserItem>[] = [
  {
    key: "userName",
    max: 32,
    pattern: PatternKey.code,
  },
  {
    key: "password",
    label: "密码",
    type: FormItemComponentType.PASSWORD,
  },
  {
    key: "phonenumber",
    pattern: PatternKey.cellphone,
  },
  {
    key: "email",
    pattern: PatternKey.email,
  },
  {
    key: "roleIds",
    label: "所属角色",
    type: FormItemComponentType.SELECT,
    async getData() {
      const roleData = await getRoleList();
      return (roleData ? roleData : [])
        .filter((el) => !el.admin)
        .map((el) => ({ label: el.roleName, value: el.roleId }));
    },
    props: {
      options: [],
      mode: "multiple",
    },
  },
  {
    key: "remark",
    type: FormItemComponentType.TEXTAREA,
    max: 256,
  },
];

const showOptions = ref<ShowCURDModalOptions>();

const { tableData, tableLoading, curd, reloadTable } = useCURD<PartialUserItem>({
  getDataUrl: Api.userList,
  createUrl: Api.user,
  updateUrl: Api.user,
  deleteUrl: Api.user,
});

const operData: OperItem<PartialUserItem>[] = [
  {
    label: t("common.edit"),
    handler: showUpdateModal,
  },
];
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record) {
  showOptions.value = { action: CURDAction.DELETE, record };
}

const curdDialogIns = shallowRef<CURDDialogExpose<PartialUserItem>>();
function open(e: CURDModalEvent<PartialUserItem>) {
  if (curdDialogIns.value) {
    curdDialogIns.value.toggleField("password", e.action === CURDAction.UPDATE);
  }
}

async function getDetail(record: PartialUserItem): Promise<PartialUserItem | null | undefined> {
  const data = await getUserDetail(record.userId as number);
  return data ? { roleIds: data.roleIds } : data;
}

function handleResetPwd(record: PartialUserItem) {
  InfoModal.warningConfirm({
    title: "提示",
    content: "确认重置该用户密码吗？",
    async onOk() {
      const re = await resetPwd({
        userId: record.userId as number,
        password: "123456",
      });
      if (re !== null) {
        InfoModal.success({
          title: "重置成功",
          content: "新密码为123456",
        });
      }
    },
  });
}

function beforeUpdateModel(record: PartialUserItem) {
  if (!record.roleIds) {
    record.roleIds = [];
  }
}
function beforeOk(e: CURDModalEvent<PartialUserItem>) {
  if (e.action === CURDAction.UPDATE && e.model) {
    //不能修改密码
    delete e.model.password;
  }
}
</script>
